package com.yl.mybatis.scanner;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: TODO
 * @author: yoozhoo
 * @modified By: yoozhoo
 * @date: Created in 2021/1/4 6:17 下午
 * @version:v1.0
 */
public class SimpleScanner {

    private String baseScanPath;


    public SimpleScanner(String baseScanPath) {
        this.baseScanPath = baseScanPath;
    }

    public void setBaseScanPath(String baseScanPath) {
        this.baseScanPath = baseScanPath;
    }

    public List<Class<?>> doScan() {
        List<Class<?>> beanClasses = new ArrayList<>();

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        baseScanPath = baseScanPath.replace(".", "/");
        URL resource = classLoader.getResource(baseScanPath);
        File file = new File(resource.getFile());

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length < 1) {
                return beanClasses;
            }
            for (File f : files) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    String className = fileName
                        .substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    //mac 和windows可能会有区别
                    className = className.replace("/", ".");
                    try {
                        Class<?> clazz = classLoader.loadClass(className);
                        beanClasses.add(clazz);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return beanClasses;
    }
}
